/**
 * Copyright (c) 2017, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.waleychain.exchange.core.utils;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串工具类
 * @author chenx
 * @date 2017年7月6日 下午3:49:21
 * @version 1.0
 */
public class StringUtils {

	private final static String CHARTSET = "UTF-8";
	
	/**
	 * 私用构造主法.因为此类是工具类.
	 */
	private StringUtils() {
	}

	/**
	 * URL解码
	 * @param string
	 * @return
	 */
	public static String urlDecode(String string) {
		try {
			if (isBlank(string)) {
				return null;
			}
			
			return URLDecoder.decode(string, CHARTSET);
		} catch (UnsupportedEncodingException e) {
		}
		
		return string;
	}

	/**
	 * URL编码
	 * 
	 * @param string
	 * @return
	 */
	public static String urlEncode(String string) {
		try {
			return URLEncoder.encode(string, CHARTSET);
		} catch (UnsupportedEncodingException e) {
		}
		return string;
	}

	/**
	 * URL重定向
	 * 
	 * @param redirect
	 * @return
	 */
	public static String urlRedirect(String redirect) {
		try {
			redirect = new String(redirect.getBytes(CHARTSET), "ISO8859_1");
		} catch (UnsupportedEncodingException e) {
		}
		return redirect;
	}

	/**
	 * 空判断[不去空格]
	 * 
	 * @param strings
	 *            字符串可变参数
	 * @return
	 */
	public static boolean areNull(String... strings) {
		if (strings == null || strings.length == 0)
			return false;

		for (String string : strings) {
			if (string != null) {
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 非空判断[不去空格]
	 * 
	 * @param strings
	 *            字符串可变参数
	 * @return
	 */
	public static boolean areNotEmpty(String... strings) {
		if (strings == null || strings.length == 0)
			return false;

		for (String string : strings) {
			if (string == null || "".equals(string)) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 非空判断[不去空格]
	 * 
	 * @param string
	 *            字符串
	 * @return
	 */
	public static boolean isNotEmpty(String string) {
		return string != null && !string.equals("");
	}

	/**
	 * 空判断[不去空格]
	 * 
	 * @param string
	 *            字符串
	 * @return
	 */
	public static boolean isEmpty(String string) {
		return string == null || string.equals("");
	}
	
	/**
	 * 非空判断[去空格]
	 * 
	 * @param strings
	 *            字符串可变参数
	 * @return
	 */
	public static boolean areNotBlank(String... strings) {
		if (strings == null || strings.length == 0)
			return false;

		for (String string : strings) {
			if (string == null || "".equals(string.trim())) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 非空判断[去空格]
	 * 
	 * @param string
	 *            字符串
	 * @return
	 */
	public static boolean isNotBlank(String string) {
		return string != null && !string.trim().equals("");
	}

	/**
	 * 空判断[去空格]
	 * 
	 * @param string
	 * @return
	 */
	public static boolean isBlank(String string) {
		return string == null || string.trim().equals("");
	}

	/**
	 * 字符串转long
	 * 
	 * @param value
	 *            字符串
	 * @param defaultValue
	 *            默认long值
	 * @return
	 */
	public static long toLong(String value, Long defaultValue) {
		try {
			if (value == null || "".equals(value.trim()))
				return defaultValue;
			value = value.trim();
			if (value.startsWith("N") || value.startsWith("n"))
				return -Long.parseLong(value.substring(1));
			return Long.parseLong(value);
		} catch (Exception e) {
		}
		return defaultValue;
	}

	/**
	 * 字符串转int
	 * 
	 * @param value
	 *            字符串
	 * @param defaultValue
	 *            默认int值
	 * @return
	 */
	public static int toInt(String value, int defaultValue) {
		try {
			if (value == null || "".equals(value.trim()))
				return defaultValue;
			value = value.trim();
			if (value.startsWith("N") || value.startsWith("n"))
				return -Integer.parseInt(value.substring(1));
			return Integer.parseInt(value);
		} catch (Exception e) {
		}
		return defaultValue;
	}

	/**
	 * 字符串转biginteger
	 * 
	 * @param value
	 *            字符串
	 * @param defaultValue
	 *            默认bigintger值
	 * @return
	 */
	public static BigInteger toBigInteger(String value, BigInteger defaultValue) {
		try {
			if (value == null || "".equals(value.trim()))
				return defaultValue;
			value = value.trim();
			if (value.startsWith("N") || value.startsWith("n"))
				return new BigInteger(value).negate();
			return new BigInteger(value);
		} catch (Exception e) {
		}
		return defaultValue;
	}

	/**
	 * 正则查找
	 * 
	 * @param string
	 *            字符串
	 * @param regex
	 *            正则表达式
	 * @return
	 */
	public static boolean match(String string, String regex) {
		Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(string);
		return matcher.matches();
	}

	/**
	 * 判断是否是数字
	 * 
	 * @param str
	 *            字符串
	 * @return
	 */
	public static boolean isNumeric(String str) {
		if (str == null)
			return false;
		for (int i = str.length(); --i >= 0;) {
			int chr = str.charAt(i);
			if (chr < 48 || chr > 57)
				return false;
		}
		return true;
	}

	/**
	 * html编码
	 * 
	 * @param text
	 * @return
	 */
	public static String escapeHtml(String text) {
		if (isBlank(text))
			return text;

		return text.replace("<", "&lt;").replace(">", "&gt;").replace("\"", "&quot;").replace("'", "&#x27;").replace("/", "&#x2F;");
	}

	/**
	 * html解码
	 * 
	 * @param text
	 * @return
	 */
	public static String descapeHtml(String text) {
		if (isBlank(text))
			return text;

		return text.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&#x27;", "'").replace("&#x2F;", "/");
	}
	
	/**
	 * 替换某个字符
	 * @param str
	 * @param regex
	 * @param args
	 * @return
	 */
	public static String replace(String str,String regex,String... args){
		int length = args.length;
		for (int i = 0; i < length; i++) {
			str=str.replaceFirst(regex, args[i]);
		}
		return str;
	}
	
	/**
	 * 将一个字符串按指定字符截取成字符数组
	 * @param src 待操作的字符串
	 * @param sepr 截取的字符
	 * @return 返回String数组
	 */
	public static String[] split(String src, String sepr) {
		if (src == null || src.length() == 0)
			return new String[0];
		if (sepr == null || sepr.length() == 0)
			return new String[0];
		List<String> strList = new ArrayList<String>();
		int pos;
		while ((pos = src.indexOf(sepr)) != -1) {
			strList.add(src.substring(0, pos));
			src = src.substring(pos + sepr.length());
		}
		if (src.length() > 0) {
			strList.add(src);
		} else {
			strList.add("");
		}

		return (String[]) strList.toArray(new String[0]);
	}
	
	public static boolean checkStringArrisNull(String[] arr) {
		if (arr == null || arr.length <= 0) {
			return true;
		}
		
		return false;
	}
	
	/**
     * 过滤不可见字符
     */
	public static String stripNonValidXMLCharacters(String input) {
		if (input == null || ("".equals(input)))
			return "";
		StringBuilder out = new StringBuilder();
		char current;
		for (int i = 0; i < input.length(); i++) {
			current = input.charAt(i);
			if ((current == 0x9) || (current == 0xA) || (current == 0xD)
					|| ((current >= 0x20) && (current <= 0xD7FF))
					|| ((current >= 0xE000) && (current <= 0xFFFD))
					|| ((current >= 0x10000) && (current <= 0x10FFFF)))
				out.append(current);
		}
		return out.toString();
	}
	
	public static List<String> convertToList(String str1, String... other) {

		List<String> list = new ArrayList<>();
		list.add(str1);

		if (other.length > 0) {
			for (String str : other) {
				list.add(str);
			}
		}

		return list;
	}

	public static List<Integer> convertStrToIntList(String src, String sep) {

		if (isBlank(src)) {
			return null;
		}

		List<Integer> list = new ArrayList<>();

		String[] arry = StringUtils.split(src, sep);

		for (String str : arry) {
			if (!isBlank(str)) {
				list.add(Integer.parseInt(str));
			}
		}

		return list;
	}
	
	public static List<String> convertStrToList(String src, String sep) {

		if (isBlank(src)) {
			return null;
		}

		List<String> list = new ArrayList<>();

		String[] arry = StringUtils.split(src, sep);

		for (String str : arry) {
			if (!isBlank(str)) {
				list.add(str);
			}
		}

		return list;
	}

	public static List<String> convertArrToList(List<String[]> src) {

		if (src == null) {
			return null;
		}

		List<String> list = new ArrayList<>();

		for (String[] str : src) {
			list.add("23" + str[2] + str[3]);
		}

		return list;
	}

	@SuppressWarnings("deprecation")
	public static Map<String, String> convertParamsToMap(String params) {
		
		if (isBlank(params)) {
			return null;
		}
		
		params = URLDecoder.decode(params);
		
		Map<String, String> map = new HashMap<String, String>();
		String[] vxs = StringUtils.split(params, "&");
		for (String str : vxs) {
			String[] par = StringUtils.split(str, "=");
			if (par.length > 2) {
				map.put(par[0], par[1] + "=" + par[2]);
			} else {
				map.put(par[0], par[1]);
			}
		}
		
		return map;
	}
}
